package com.nizi.wordoperate.controller;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;


@RestController
@RequestMapping(value = "/api")
public class UploadController {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    private static String key = "file";
    private static String springProperties = "application.properties";

    @ResponseBody
    @RequestMapping(value = "/upload/{fileType}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String uploadFile(HttpServletRequest request, @PathVariable(value = "fileType") String fileType) {
        String result = "";
        String fileAbsolutePath = "";
        try {
            logger.info("uploadFile begin! fileType={}", fileType);
            //写本地文档
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartHttpServletRequest.getFile(key);
            String fileName = multipartFile.getOriginalFilename();
            //文件名称加随机数处理，避免重名
            fileName = fileName.substring(0, fileName.lastIndexOf(".")) + "_" + System.currentTimeMillis() % 1000 + fileName.substring(fileName.lastIndexOf("."));
            fileAbsolutePath = getUploadPath() + fileName;
            writeFile(fileAbsolutePath, multipartFile.getBytes());
        } catch (Exception e) {
            result = "上传异常";
            logger.error("uploadFile exception!", e);
            return e.getMessage();
        }
        return "ok";
    }

    //通过spring的配置文件，来获取war包的绝对路径，并将文件上传到预先准备的文件夹下
    private String getUploadPath() {
        URL url = this.getClass().getClassLoader().getResource(springProperties);
        String uploadPath = url.getPath().replace(springProperties, "upload/");
        return uploadPath;
    }

    public static void writeFile(String fileAbsolutePath, byte[] content) throws IOException {
        FileOutputStream fos = new FileOutputStream(fileAbsolutePath);
        fos.write(content);
        fos.close();
    }

}
